package com.webserver.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class HttpResquest {
    private String method;//请求方式
    private String url;//请求路径
    private String protocol;//协议版本
    private Socket socket;
    private Map<String,String> headers = new HashMap<>();//消息头的名字和对应的值

    private String line;
    private String[]data;
    public HttpResquest(Socket socket)throws IOException {
        this.socket = socket;
        parseRequestLine();
        parseHanders();
        parseContent();
    }
    private void parseRequestLine()throws IOException{
        line = readLine();
        System.out.println(line);
        data = line.split("\\s");//将请求行的内容按空格切开
        method = data[0];
        url = data[1];
        protocol = data[2];
        System.out.println("method:"+method+"  url:"+url+"   protocol"+protocol);

    }
    private void parseHanders()throws IOException{
        while(!(line = readLine()).isEmpty()) {
            System.out.println("消息头" + line);
            data = line.split(":\\s");
            headers.put(data[0], data[1]);
        }
    }
    private void parseContent(){}

    public String getMethod() {
        return method;
    }
    public String getUrl() {
        return url;
    }
    public String getProtocol() {
        return protocol;
    }
    public String getHeader(String name){
        return headers.get(name);
    }

    private String readLine()throws IOException {
        InputStream in = socket.getInputStream();
        StringBuilder builder = new StringBuilder();
        int d;
        char pre = 'a',cur = 'a';//上次 本次
        while((d = in.read())!=-1){
            cur = (char)d;
            if(pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();//返回请求行的内容

    }

}
